from typing import List
from venv import logger

from fastapi import Request
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session

from core.dao.cms_car_dao import CmsCarDao
from core.dao.cms_gaode_fence_terminal_dao import CmsGaodeFenceTerminalDao
from core.entity.vo.common import CrudResponse
from core.entity.vo.view_models import CmsGaodeFenceTerminalVO
from core.service.cms_car_service import CmsCarService
from core.service.gaode.gaode_fence_terminal_service import GaodeFenceTerminalService
from core.service.gaode.gaode_terminal_service import GaodeTerminalService
from models import CmsGaodeFenceTerminal


class CmsGaodeFenceTerminalService:
    """
    高德终端service
    """

    @classmethod
    def get_cms_gaode_fence_terminal_by_id(cls, result_db: Session, id: int):
        """
        获取参数配置列表信息service
        :param result_db: orm对象
        :param id: id
        :return: 参数配置列表信息对象
        """
        cms_gaode_fence_terminal = CmsGaodeFenceTerminalDao.get_cms_gaode_fence_terminal_by_id(result_db, id)

        return cms_gaode_fence_terminal

    @classmethod
    def get_cms_gaode_fence_terminal_by_fence_id(cls, result_db: Session, fence_id: str):
        """
        获取参数配置列表信息service
        :param result_db: orm对象
        :param fence_id: 高德围栏id
        :return: 参数配置列表信息对象
        """
        cms_gaode_fence_terminal_list = (CmsGaodeFenceTerminalDao
                                         .get_cms_gaode_fence_terminal_by_fence_id(result_db, fence_id))

        return cms_gaode_fence_terminal_list

    @classmethod
    def get_cms_gaode_fence_terminal_by_terminal_id(cls, result_db: Session, terminal_id: str):
        """
        获取参数配置列表信息service
        :param result_db: orm对象
        :param terminal_id: 高德终端id
        :return: 参数配置列表信息对象
        """
        cms_gaode_fence_terminal_list = (CmsGaodeFenceTerminalDao
                                         .get_cms_gaode_fence_terminal_by_terminal_id(result_db, terminal_id))
        return cms_gaode_fence_terminal_list

    @classmethod
    def bind_cms_gaode_fence_terminal(cls, request: Request, result_db: Session,
                                      cms_gaode_fence_terminal: CmsGaodeFenceTerminalVO) -> CrudResponse:
        """
        新增参数配置信息service
        :param request: Request对象
        :param result_db: orm对象
        :param cms_gaode_fence_terminal: 新增参数配置对象
        :return: 新增参数配置校验结果
        """
        try:
            CmsGaodeFenceTerminalDao.add_cms_gaode_fence_terminal_dao(result_db, cms_gaode_fence_terminal)
            result_db.commit()
            result = {"is_success": True, "message": "绑定成功"}
            logger.info("绑定成功: %s", cms_gaode_fence_terminal)
        except SQLAlchemyError as e:
            result_db.rollback()
            result = {"is_success": False, "message": "数据库错误: " + str(e)}
            logger.exception("数据库错误: %s", e)
        except Exception as e:
            result = {"is_success": False, "message": "未知错误: " + str(e)}
            logger.exception("未知错误: %s", e)
        return CrudResponse(**result)

    @classmethod
    def bind_cms_gaode_fence_terminal_batch(cls, request: Request, result_db: Session,
                                            cms_gaode_fence_terminal_list: List[
                                                CmsGaodeFenceTerminalVO]) -> CrudResponse:
        """
        新增参数配置信息service
        :param request: Request对象
        :param result_db: orm对象
        :param cms_gaode_fence_terminal: 新增参数配置对象
        :return: 新增参数配置校验结果
        """
        try:
            # for cms_gaode_fence_terminal in cms_gaode_fence_terminal_list:
            #     # 查看车辆是否加入终端（不需要）
            #     tid_ = None
            #     query_terminal = GaodeTerminalService.query_terminal(cms_gaode_fence_terminal.service_id,
            #                                                          cms_gaode_fence_terminal.terminal_id)
            #     if ('errcode' in query_terminal and query_terminal['errcode'] == 10000
            #             and ('data' not in query_terminal or query_terminal['data']['count'] is None)):
            #         add_terminal = GaodeTerminalService.add_terminal(cms_gaode_fence_terminal.service_id,
            #                                                          cms_gaode_fence_terminal.terminal_id,
            #                                                          cms_gaode_fence_terminal.terminal_id)
            #         if 'errcode' in add_terminal and add_terminal['errcode'] == 10000:
            #             tid_ = add_terminal['data']['tid']
            #     elif ('errcode' in query_terminal and query_terminal['errcode'] == 10000
            #           and query_terminal['data']['results'][0]['tid'] is not None):
            #         tid_ = query_terminal['data']['results'][0]['tid']
            #     if tid_:
            #         # 更新车辆在高德的设备id
            #         CmsCarDao.update_car_by_car_id(result_db, cms_gaode_fence_terminal.terminal_id,
            #                                        tid_)
            #         terminal = GaodeFenceTerminalService.bind_fence_terminal(cms_gaode_fence_terminal.service_id,
            #                                                                  cms_gaode_fence_terminal.fence_id,
            #                                                                  tid_)
            #         cms_gaode_fence_terminal.tid = tid_
            #         if 'errcode' in terminal and terminal['errcode'] != 10000:
            #             raise ValueError(f"高德绑定车辆失败{terminal}")
            #     else:
            #         raise ValueError(f"高德绑定车辆失败{query_terminal}")
            CmsGaodeFenceTerminalDao.add_cms_gaode_fence_terminal_dao_list(result_db, cms_gaode_fence_terminal_list)
            result = {"is_success": True, "message": "绑定成功"}
            logger.info("绑定成功: %s", cms_gaode_fence_terminal_list)
        except SQLAlchemyError as e:
            result_db.rollback()
            result = {"is_success": False, "message": "数据库错误: " + str(e)}
            logger.exception("数据库错误: %s", e)
        except Exception as e:
            result = {"is_success": False, "message": "未知错误: " + str(e)}
            logger.exception("未知错误: %s", e)
        return CrudResponse(**result)

    @classmethod
    def unbind_cms_gaode_fence_terminal_batch(cls, result_db: Session, fence_id: str) -> CrudResponse:
        """
        新增参数配置信息service
        :param request: Request对象
        :param result_db: orm对象
        :param cms_gaode_fence_terminal: 新增参数配置对象
        :return: 新增参数配置校验结果
        """
        try:
            # by_fence_id: List[
            #     CmsGaodeFenceTerminal] = CmsGaodeFenceTerminalDao.get_cms_gaode_fence_terminal_by_fence_id(result_db,
            #                                                                                                fence_id)
            # for e in by_fence_id:
            #     GaodeTerminalService.delete_terminal(e.service_id, e.fence_id, e.tid)
            # # 更新车辆在高德的设备id
            # CmsCarDao.update_car_by_car_id(result_db, e.terminal_id,
            #                                "")
            CmsGaodeFenceTerminalDao.delete_cms_gaode_fence_terminal_by_fence_id(result_db, fence_id)
            result_db.commit()
            result = {"is_success": True, "message": "解绑成功"}
            logger.info("解绑成功: %s", "")
        except SQLAlchemyError as e:
            result_db.rollback()
            result = {"is_success": False, "message": "数据库错误: " + str(e)}
            logger.exception("数据库错误: %s", e)
        except Exception as e:
            result = {"is_success": False, "message": "未知错误: " + str(e)}
            logger.exception("未知错误: %s", e)
        return CrudResponse(**result)

    @classmethod
    async def unbind_cms_gaode_fence_terminal(cls, request: Request, result_db: Session,
                                              cms_gaode_fence_terminal: CmsGaodeFenceTerminalVO):
        """
        编辑参数配置信息service
        :param request: Request对象
        :param result_db: orm对象
        :param cms_gaode_fence_terminal: 编辑参数配置对象
        :return: 编辑参数配置校验结果
        """
        result = GaodeFenceTerminalService.unbind_fence_terminal(cms_gaode_fence_terminal.service_id,
                                                                 cms_gaode_fence_terminal.fence_id,
                                                                 cms_gaode_fence_terminal.terminal_id)
        if result['errcode'] == 10000:
            try:
                CmsGaodeFenceTerminalDao.delete_cms_gaode_fence_terminal_dao(result_db,
                                                                             cms_gaode_fence_terminal.service_id,
                                                                             cms_gaode_fence_terminal.fence_id,
                                                                             cms_gaode_fence_terminal.terminal_id)
                result_db.commit()
                result = dict(is_success=True, message='解绑成功')
            except Exception as e:
                result_db.rollback()
                result = dict(is_success=False, message=str(e))
        else:
            result = dict(is_success=False, message=str(result['errmsg']))
        return CrudResponse(**result)
